﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bzure.Common.Data;
using Bzure.Security.Principal;

namespace Bzure.Apps.Security.DataAccess
{
    public class PasswordTokenRepository : RepositoryBase
    {
        static PasswordTokenRepository()
        {
            PasswordToken entity = new PasswordToken();
            Type type = entity.GetType();
            AppendDataMap(type, "CreateTime", () => entity.CreateTime);
            AppendDataMap(type, "Expire", () => entity.Expire);
            AppendDataMap(type, "Token", () => entity.Token);
            AppendDataMap(type, "UserName", () => entity.UserName);
            ResultMapDelegate<PasswordToken> queryMap = PasswordToken_Map;
            QueryMapContainer[entity.GetType()] = queryMap;

        }
        public PasswordTokenRepository(Bzure.Common.Transactions.ITransactionSupport contractProvider)
            : base(contractProvider)
        {
        }
        public override string TableName
        {
            get
            {
                return "T_Security_PasswordTokens";
            }
        }
        /// <summary>
        /// 客户实体数据映射
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static PasswordToken PasswordToken_Map(DataReader reader)
        {
            PasswordToken PasswordToken = new PasswordToken
            {
                CreateTime = reader.GetDateTime("CreateTime"),
                Expire = reader.GetDateTime("Expire"),
                Token = reader.GetString("Token"),
                UserName = reader.GetString("UserName")
            };
            return PasswordToken;
        }
        public PasswordToken GetUserPasswordToken(string UserName)
        {
            string sql = string.Format("SELECT TOP 1 * FROM {0} WHERE UserName=@UserName", this.TableName);
            return new SqlEntityMap<PasswordToken>(this.ContractProvider, sql)
              .AddString("UserName", UserName)
              .SetMap(PasswordToken_Map)
              .AsSingle();
        }
        /// <summary>
        /// 获取用户的密码找回令牌
        /// </summary>
        /// <param name="Token">令牌</param>
        /// <returns></returns>
        public PasswordToken GetPasswordToken(string Token)
        {
            string sql = string.Format("SELECT TOP 1 * FROM {0} WHERE Token=@Token", this.TableName);
            return new SqlEntityMap<PasswordToken>(this.ContractProvider, sql)
              .AddString("Token", Token)
              .SetMap(PasswordToken_Map)
              .AsSingle();
        }
    }
}
